<?php
namespace app\common\model\blfyy;
use app\common\model\BaseModel;
use think\Db;
use chrome\ChromePhp;//引入chromephp插件
use common\Common;//公共函数

/**
 * 提供表单管理服务
 * @name LibForm.php
 * @package blfyy
 * @category model
 * @link http://www.chanekeji.com
 * @author syben
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2021-03-11
 */
class LibForm extends BaseModel{
	protected $m_form;

	/**
	 * 构造函数
	 */
	public function __construct(){
		$this->m_form = db('blf_form');
		parent::__construct();
	}
	
	/**
	 * 添加表单信息
	 */
	public function addForm($condition){
		try {
			$condition['add_time'] = Common::getTime();
			$reslut = $this->m_form->insertGetId($condition);		
			if(true == $reslut){
				return Common::errorArray(0, "添加成功",$reslut);
			}else{
				return Common::errorArray(1, "添加失败", $reslut);
			}
		}catch (Exception $ex){
			$this->errorLog(__CLASS__, __FUNCTION__, $ex);
			return  Common::errorArray(1, "数据库操作失败", $ex);
		}
	}
	
	
	
	/**
	 * 查询单个表单信息
	 * @param $condition
	 * @param array $result
	 */
	public function findForm($condition='',$field=''){		
		try {
			$reslut = $this->m_form->where($condition)->field($field)->find();	
					
			if(true == $reslut){
				return Common::errorArray(0, "查询成功",$reslut);
			}else{
				return Common::errorArray(1, "查询为空", $reslut);
			}
		}catch (Exception $ex){
			$this->errorLog(__CLASS__, __FUNCTION__, $ex);
			return  Common::errorArray(1, "数据库操作失败", $ex);
		}
	}
	
	/**
	 * 查询多个表单信息
	 * @param $condition
	 * @param $limit
	 * @param $field
	 * @param $sort
	 * @param array $result
	 */
	public function findAllForm($condition='',$limit='',$field='',$sort='add_time desc'){		
		try {
			$reslut = $this->m_form->where($condition)->order($sort)->limit($limit)->field($field)->select();			
			if(true == $reslut){
				return Common::errorArray(0, "查询成功",$reslut);
			}else{
				return Common::errorArray(1, "查询为空", $reslut);
			}
		}catch (Exception $ex){
			$this->errorLog(__CLASS__, __FUNCTION__, $ex);
			return  Common::errorArray(1, "数据库操作失败", $ex);
		}
	}
	
	/**
	 * 更新表单信息
	 * @param $condition
	 * @param $userInfo
	 * @param array $result
	 */
	public function updateForm($condition,$userInfo){
		try {
			$reslut = $this->m_form->where($condition)->update($userInfo);;		
			if(true == $reslut){
				return Common::errorArray(0, "更新成功",$reslut);
			}else{
				return Common::errorArray(1, "更新失败", $reslut);
			}
		}catch (Exception $ex){
			$this->errorLog(__CLASS__, __FUNCTION__, $ex);
			return  Common::errorArray(1, "数据库操作失败", $ex);
		}
	}
	
	/**
	 * 删除表单信息
	 * @param $condition
	 * @param array $result
	 */
	public function deleteForm($ids){
		$condition = array('id'=>array('in',$ids));
		try {
			$reslut = $this->m_form->where($condition)->delete();;		
			if(true == $reslut){
				return Common::errorArray(0, "删除成功",$reslut);
			}else{
				return Common::errorArray(1, "删除失败", $reslut);
			}
		}catch (Exception $ex){
			$this->errorLog(__CLASS__, __FUNCTION__, $ex);
			return  Common::errorArray(1, "数据库操作失败", $ex);
		}
	}
	
	/**
	 * 字段值加1
	 * @param $condition
	 * @param string $field
	 * @param int $optval
	 * @param array $reslut
	 */
	public function increaseField($condition,$field,$optval = 1){
		try {
			$reslut = $this->m_form->where($condition)->setInc($field,$optval);;		
			if(true == $reslut){
				return Common::errorArray(0, "修改成功",$reslut);
			}else{
				return Common::errorArray(1, "修改失败", $reslut);
			}
		}catch (Exception $ex){
			$this->errorLog(__CLASS__, __FUNCTION__, $ex);
			return  Common::errorArray(1, "数据库操作失败", $ex);
		}
	}
	
	/**
	 * 字段值减1
	 * @param $condition
	 * @param string $field
	 * @param int $optval
	 * @param array $reslut
	 */
	public function decreaseField($condition,$field,$optval = 1){
		try {
			$reslut = $this->m_form->where($condition)->setDec($field,$optval);;		
			if(true == $reslut){
				return Common::errorArray(0, "修改成功",$reslut);
			}else{
				return Common::errorArray(1, "修改失败", $reslut);
			}
		}catch (Exception $ex){
			$this->errorLog(__CLASS__, __FUNCTION__, $ex);
			return  Common::errorArray(1, "数据库操作失败", $ex);
		}
	}
	
	/**
	 * 分页获取数据表单信息
	 */
	public function pagingForm($page,$conditionList,$sort = '',$orList = null){
		$reslut = Common::paging('blf_form',$page,$conditionList,$sort,$orList);
		return  $reslut;  		
	}
	
	/***************** 导出订单功能  **********************/
	
	/**
	 * 获取订单列表
	 * @param array $conditions
	 * @param string $sort
	 * @param string $keywords
	 * @param string $createTime
	 * @param string $endTime
	 * @return array $result
	 */
	function getAllForms($sort = 'add_time desc',$conditions = null,  $keywords = null,$createTime = null,$endTime = null){
		if(empty($sort)){
			$sortstr = "";
		}
		else if(is_array($sort)){
			if(count($sort) == 0){
				$sortstr = "";
			}
			else{
				$sortstr = "ORDER BY";
				foreach ($sort as $key => $sortitem){
					$sortarray[] = " {$sortitem['field']} {$sortitem['orderby']}";
				}
				$sortstr = $sortstr.join(',', $sortarray);
			}
		}
		else if(is_string($sort)){
			$sortstr = "ORDER BY ".$sort;
		}
		
		if(empty($conditions)&&(empty($keywords)&&(empty($createTime))&&(empty($endTime)))){
			$sql = "SELECT * FROM blf_form {$sortstr}";
		}else {
			//循环conditions数组，生成执行查询操作的sql语句
			$where = "";
			if (is_array ( $conditions ) || is_array($keywords) || is_array($createTime) || is_array($endTime)) {
				$join = array ();
					
				if (!empty($conditions)) {
					foreach ( $conditions as $key => $condition ) {
						//检测具体条件是否为数组，如果是则拆分条件并用OR连接，两边加上括号
						if(is_array($condition)){
							$join2=array();
							foreach ($condition as $key2 => $value){
								$value = Common::isNumberic($value);
								$join2[]="{$key} = {$value}";
							}
							$join[] = '('.join( " OR ", $join2 ).')';
						}
						else{
							//如果具体条件不是数组，则过滤字符串之后直接赋值
							$condition = Common::isNumberic( $condition );
							$join [] = "{$key} = {$condition}";
						}
					}
				}
		
				//模糊查询条件
				if(!empty($keywords)){
					foreach ($keywords as $key3 => $keyword){
						$join [] = $key3." LIKE CONCAT('%','$keyword','%')";
					}
				}
		
				//时间段条件
				if(!empty($createTime)){
					if ($createTime['from_add_time']!='') {
						$join [] = "add_time >='".$createTime['from_add_time']."'";
					}
					if ($createTime['to_add_time']!='') {
						$join [] = " add_time <='".$createTime['to_add_time']."'";
					}
				}
		
				//时间段条件
				if(!empty($endTime)){
					if ($endTime['from']!='') {
						$join [] = " end_time >='".$endTime['from']."'";
					}
					if ($endTime['to']!='') {
						$join [] = " end_time <='".$endTime['to']."'";
					}
				}
		
				//将所有的条件用AND连接起来
				$where = "WHERE " . join ( " AND ", $join );
			} else {
				if (null != $conditions)
					$where = "WHERE " . $conditions;
			}
			//根据$sort的值 选择要排序的字段
			$sql = "SELECT * FROM blf_form {$where} {$sortstr}";
		}
//		echo $sql;die;
		//查询数据库
		try {
			$result ['dataList'] = Db::query($sql);
		} catch (Exception $ex) {
			$result ["errorCode"] = 2;
			$result ["errorInfo"] = '数据库操作失败';
			$result ["result"] = array (
					"isSuccess" => FALSE
			);
			return $result;
		}

		return Common::errorArray(0, "获取数据成功", $result);
	}
	
	/**
	 * 导出excel
	 * @param array $oriData
	 */
    function importExcel($oriData){
        $headArr = array("用户昵称","真实姓名","openID","手机号","微信号","平台名称","收益","提单时间");
        $data = array();
        for($i = 0;$i < count($oriData);$i++){
            $data[$i][0] = " ".$oriData[$i]['nick_name'];
            $data[$i][1] = " ".$oriData[$i]['name'];
            $data[$i][2] = " ".$oriData[$i]['openID'];
            $data[$i][3] = " ".$oriData[$i]['phone'];
            $data[$i][4] = " ".$oriData[$i]['weChat'];
			$data[$i][5] = " ".$oriData[$i]['platform'];
			$data[$i][6] = " ".$oriData[$i]['interests'];
            $data[$i][7] = " ".$oriData[$i]['add_time'];
        }
        $this->getExcel($headArr,$data);
    }
	
	/**
	 * 导出excel 的配置
	 * @param array $headArr
	 * @param array $data
	 */
	private function getExcel($headArr,$data){
		if(empty($data) || !is_array($data)){
			die("data must be a array");
		}
		
		$date = date("Y_m_d",time());
		$fileName = "表单_".date ( 'YmdHis', time () ).".xlsx";
	
		//创建新的PHPExcel对象
		$objPHPExcel = new \PHPExcel();
		$objProps = $objPHPExcel->getProperties();
	
		//设置表头
		$key = ord("A");
		foreach($headArr as $v){
			$colum = chr($key);
			$objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
			$key += 1;
		}
	
		$column = 2;
		$objActSheet = $objPHPExcel->getActiveSheet();
		foreach($data as $key => $rows){ //行写入
			$span = ord("A");
			foreach($rows as $keyName=>$value){// 列写入
				$j = chr($span);
				$objActSheet->setCellValue($j.$column, $value);
				$span++;
			}
			$column++;
		}
	
		$fileName = iconv("utf-8", "gb2312", $fileName);
		//重命名表
		$objPHPExcel->getActiveSheet()->setTitle('Simple');
		//设置活动单指数到第一个表,所以Excel打开这是第一个表
		$objPHPExcel->setActiveSheetIndex(0);
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
		//将输出重定向到一个客户端web浏览器(Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header("Content-Disposition: attachment; filename=\"$fileName\"");
		header('Cache-Control: max-age=0');
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWriter->save('php://output');
		exit;
	}
	
}


?>